package com.chanyachting.emall.util;

import java.util.*;
import java.text.*;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class DateUtil {

	private final static SimpleDateFormat DateTimeFormatter = new SimpleDateFormat(
			"yyyy.MM.dd HH:mm:ss");
	private final static SimpleDateFormat DateFormatter = new SimpleDateFormat(
			"yyyy.MM.dd");
	private final static SimpleDateFormat TimeFormatter = new SimpleDateFormat(
			"HH:mm:ss");
	private final static SimpleDateFormat DateTimeTrimFormatter = new SimpleDateFormat(
			"yyyyMMddHHmmss");
	private final static SimpleDateFormat DateTrimFormatter = new SimpleDateFormat(
			"yyyyMMdd");
	private final static SimpleDateFormat TimeTrimFormatter = new SimpleDateFormat(
			"HHmmss");

	private final static SimpleDateFormat chineseFormatter = new SimpleDateFormat(
			"yyyy年MM月dd旄1�7 HH点mm刄1�7");

	private static Log log = LogFactory.getLog(DateUtil.class);

	private DateUtil() {
	}

	public static String convertDateTime2String(Date date) {
		return DateTimeFormatter.format(date);
	}

	public static String convertDate2String(Date date) {
		return DateFormatter.format(date);
	}

	public static String convertTime2String(Date date) {
		return TimeFormatter.format(date);
	}

	public static String currentDateTimeString() {
		return DateTimeFormatter.format(new Date());
	}

	public static String currentDateTimeStringTrim() {
		return DateTimeTrimFormatter.format(new Date());
	}

	public static String currentDateString() {
		return DateFormatter.format(new Date());
	}

	public static String currentDateStringTrim() {
		return DateTrimFormatter.format(new Date());
	}

	public static String currentTimeString() {
		return TimeFormatter.format(new Date());
	}

	public static String currentTimeStringTrim() {
		return TimeTrimFormatter.format(new Date());
	}

	public static String convertYear2CYear(String str) throws Exception {
		if (str == null || str.trim().length() < 4)
			return str;
		String year = str.substring(0, 4);
		int _year = Integer.parseInt(year);
		_year -= 11;
		return (_year % 100) + str.substring(4);
	}

	/***************************************************************************
	 * 获得当前日期的字符串形式 格式 yyyy-MM-dd HH:mm:ss
	 * 
	 * @return
	 */
	public static String getToday() {
		Calendar calendar = Calendar.getInstance();

		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		StringBuffer bdate = new StringBuffer(formatter.format(calendar
				.getTime()));

		return bdate.toString();
	}

	/**
	 * @param timestamp
	 * @return
	 */
	public static String convertDateToString(Date date) {
		return chineseFormatter.format(date);
	}

	/**
	 * 处理日期函数
	 * 
	 * @parame 字符串 格式为 “yy/mm/dd” 例“2000/10/17”
	 * @return 字符串 格式为 “yy/mm/dd hh:mm:ss” 例 “2000/10/17 00：00：00”
	 *         该返回值可以直接插入到数据库中 类型为 DATE 的字段中
	 */
	public static String getDate(String sDate) {
		try {
			SimpleDateFormat formatter = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");

			Date fromdate = new Date(sDate);

			StringBuffer bdate = new StringBuffer(formatter.format(fromdate));

			return bdate.toString();
		} catch (Exception e) {
			// e.printStackTrace();
			return sDate;
		}
	}

	// 截取表示时间字符串的指定长度
	public static String subStringDate(String date) {

		if (date != null && date.length() > 15) {
			return date.substring(0, 16);
		}

		return "";
	}
	
	
	/***
	 * 获得指定日期到当前时间的年份差
	 * @param date  指定格式 “YYYY-MM-DD”
	 * @return  如果指定时间大于当前时间返回负整数，否则返回正整数
	 */
	public static int getDifferenceFromTodayForYear(String date){
		
		if(date==null || date.trim().equals("")) return 0;
		
		String now=DateUtil.getDate();
		
		String [] temp=StringUtil.toArray(now);
		
		int nowYear=Integer.parseInt(temp[0]);
		
		temp=StringUtil.toArray(date);
		
		int dateYear=Integer.parseInt(temp[0]);
		
		return nowYear-dateYear;
		
	}
	

	/***************************************************************************
	 * 获得指定时间 于当前时间的 天数差 (当前时间天数 减去 指定时间天数) 如果指定时间比当前时间小 则 返回一个大于0的整数 否则返回一个
	 * 小于或等于0 的整数 异常情况下返回 999
	 * 
	 * @param from_date
	 * @return
	 */
	public static int getDifferenceFromToday(String from_date) {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		try {
			Date from_date_d = sdf.parse(from_date);

			Calendar calendar = Calendar.getInstance();
			Date to_day = calendar.getTime();

			calendar.setTime(from_date_d);

			int from_day = calendar.get(Calendar.DAY_OF_YEAR);

			log.debug("----from_day int=" + from_day);

			calendar.setTime(to_day);

			int to_day_int = calendar.get(Calendar.DAY_OF_YEAR);

			log.debug("----to_day int=" + to_day);

			return to_day_int - from_day;

		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return 999;
	}

	// 获得2个日期的时间差
	public static int getDifferenceFromDate(String from_date, String to_date) {

		try {

			log.debug("---from_date=" + from_date);
			log.debug("---to_date=" + to_date);

			Calendar calendar = Calendar.getInstance();

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			Date from_date_d = sdf.parse(from_date);

			Date to_date_d = sdf.parse(to_date);

			calendar.setTime(from_date_d);

			int from_day = calendar.get(Calendar.DAY_OF_YEAR);

			log.debug("----from_day int=" + from_day);

			calendar.setTime(to_date_d);

			int to_day = calendar.get(Calendar.DAY_OF_YEAR);

			log.debug("----to_day int=" + to_day);

			return to_day - from_day;
		} catch (Exception e) {
			e.toString();
			log.error(e);
		}

		return 999;
	}

	/***************************************************************************
	 * 将string 转换成 calendar
	 * 
	 * @param date
	 * @return
	 */
	public static Calendar getCalendarFormString(String date) {
		Calendar temp = Calendar.getInstance();

		java.util.Date temp_date = getDateFormString(date);

		temp.setTime(temp_date);

		return temp;
	}

	/***************************************************************************
	 * 将 string 转换成 java.util.date
	 * 
	 * @param date
	 * @return
	 */
	public static Date getDateFormString(String date) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		Date temp_date = null;
		try {
			temp_date = formatter.parse(date);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return temp_date;
	}

	/***************************************************************************
	 * 判断 一个时间 是否在 标志时间之前 如果比标志时间小 返回 true 否则返回 false
	 * 
	 * @param order_date
	 * @param tag_date
	 * @return
	 */
	public static boolean ifbefore(String order_date, String tag_date) {
		boolean temp = true;

		Calendar order_date_calendar = getCalendarFormString(order_date);

		Calendar tag_date_calendar = getCalendarFormString(tag_date);

		// 如果 时间 在标志时间之前
		if (order_date_calendar.before(tag_date_calendar)) {
			temp = true;
		} else {
			temp = false;
		}

		return temp;
	}

	/***************************************************************************
	 * 获得当前系统时间 并转换成字符串 格式 yyyy-MM-dd HH:mm:ss
	 * 
	 * @return
	 */
	public static String getDate() {
		Calendar calendar = Calendar.getInstance();

		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		StringBuffer bdate = new StringBuffer(formatter.format(calendar
				.getTime()));

		return bdate.toString();

	}

	/***************************************************************************
	 * 返回系统当前时间 之后的指定天数的 时间， 格式为 "yyyy-MM-dd HH:mm:ss"
	 * 
	 * @param days
	 * @return
	 */
	public static String getAfterDate(int days) {
		Calendar calend = Calendar.getInstance(); // 获得当前日期

		calend.add(Calendar.DAY_OF_MONTH, days); // 在当前日期上+7天

		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		StringBuffer bdate = new StringBuffer(formatter
				.format(calend.getTime()));

		return bdate.toString();
	}

	/**
	 * 取得当前日期
	 * 
	 * @param none
	 * @return String currentDate(format: yyyyMMdd)
	 * @exception none
	 */
	public static String getCurrentDate() {
		Calendar calendar = Calendar.getInstance();
		int tYear = calendar.get(Calendar.YEAR);
		int tMonth = calendar.get(Calendar.MONTH) + 1;
		int tDate = calendar.get(Calendar.DATE);
		return String.valueOf(tYear * 10000 + tMonth * 100 + tDate);
	}

	/***************************************************************************
	 * 取得日期前后N月的日期
	 * 
	 * @param date(format:
	 *            yyyyMMdd)
	 * @param i
	 *            (第N日,正数表示后几月，负数表示前几月)
	 * @author nilomiao
	 **************************************************************************/
	public static String getNMonth(String date, int i) {
		String result = "";
		try {
			SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");

			if (date.length() == 8) {
				formatter = new SimpleDateFormat("yyyyMMdd");
			} else if (date.length() == 6) {
				formatter = new SimpleDateFormat("yyyyMM");
			}

			java.util.Date theDate = formatter.parse(date);

			theDate.setMonth(theDate.getMonth() + i);
			result = formatter.format(theDate);

		} catch (ParseException e) {
			e.printStackTrace();
		}

		return result;
	}
	
	
	
	public static String getNMonth1(String date, int i) {
		String result = "";
		try {
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			if (date.length() == 10) {
				formatter = new SimpleDateFormat("yyyy-MM-dd");
			} else if (date.length() == 7) {
				formatter = new SimpleDateFormat("yyyy-MM");
			}

			java.util.Date theDate = formatter.parse(date);

			theDate.setMonth(theDate.getMonth() + i);
			result = formatter.format(theDate);

		} catch (ParseException e) {
			e.printStackTrace();
		}

		return result;
	}


	/***************************************************************************
	 * 取得日期前后N日的日期
	 * 
	 * @param date(format:
	 *            yyyyMMdd)
	 * @param i
	 *            (第N日,正数表示后几日，负数表示前几日)
	 * @author nilomiao
	 **************************************************************************/
	public static String getNDay(String date, int i) {
		String result = "";
		try {
			SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");

			if (date.length() == 8) {
				formatter = new SimpleDateFormat("yyyyMMdd");
			}

			java.util.Date theDate = formatter.parse(date);
			theDate.setDate(theDate.getDate() + i);
			result = formatter.format(theDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return result;
	}

	/***************************************************************************
	 * 取得日期前后N小时的日期
	 * 
	 * @param date（格式为20050101）
	 * @param i
	 *            (第N日,正数表示后几小时，负数表示前几小时)
	 * @author nilomiao
	 **************************************************************************/
	public static String getNHour(String date, int i) {
		String result = "";
		try {
			SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");

			if (date.length() == 10) {
				formatter = new SimpleDateFormat("yyyyMMddHH");
			}

			java.util.Date theDate = formatter.parse(date);
			theDate.setHours(theDate.getHours() + i);
			result = formatter.format(theDate);

		} catch (ParseException e) {
			e.printStackTrace();
		}
		return result;
	}

	/***************************************************************************
	 * 从开始时间计时,算出到目前为止还剩时间
	 * 
	 * @param date（格式为20050101121212）
	 * @param continualDays
	 * @return 剩余时间 x天x小时x分钟x秒
	 * @author nilomiao
	 **************************************************************************/
	public static String countDown(String startDateStr, float continualDays) {
		String result = "";
		try {
			SimpleDateFormat formatter = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			Date startDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
					.parse(startDateStr);
			Date nowDate = new Date();

			long cutLong = new Float(24F * 3600F * 1000F * continualDays)
					.longValue();
			long useLong = nowDate.getTime() - startDate.getTime();

			Date rawDate = formatter.parse("0000-00-00 00:00:00");
			rawDate.setTime(rawDate.getTime() + cutLong - useLong);

			result = rawDate.getDay() + "天" + rawDate.getHours() + "小时"
					+ rawDate.getMinutes() + "分钟" + rawDate.getSeconds() + "秒";

		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

	/***************************************************************************
	 * 转换日期格式
	 * 
	 * @param string(YYYY/MM/DD,YYYY-MM-DD HH:MM:SS)
	 * @return String YYYYMMDD,YYYYMMDDHHMMSS
	 * @author nilomiao
	 **************************************************************************/
	public static String getSimpleFormat(String strDate) {
		if (strDate.length() == 10) {
			return strDate.substring(0, 4) + strDate.substring(5, 7)
					+ strDate.substring(8, 10);

		} else if (strDate.length() >= 19) {
			return strDate.substring(0, 4) + strDate.substring(5, 7)
					+ strDate.substring(8, 10) + strDate.substring(11, 13)
					+ strDate.substring(14, 16) + strDate.substring(17, 19);

		} else {
			return null;
		}
	}

	/***************************************************************************
	 * 转换日期格式
	 * 
	 * @param string YYYYMMDD,YYYYMMDDHHMMSS
	 * @return String (YYYY/MM/DD,YYYY-MM-DD,YYYY/MM/DD
	 *            HH:MM:SS, YYYY-MM-DD HH:MM:SS)
	 * @author nilomiao
	 **************************************************************************/
	public static String getFullFormat(String strDate) {
		if (strDate.length() == 8) {
			return strDate.substring(0, 4) + "/" + strDate.substring(4, 6)
					 + "/" + strDate.substring(6, 8);

		} else if (strDate.length() >= 14) {
			return strDate.substring(0, 4) + "/" + strDate.substring(4, 6)
			 + "/" + strDate.substring(6, 8)+ " " + strDate.substring(8, 10)
					+ ":" + strDate.substring(10, 12) + ":" + strDate.substring(12, 14);

		} else {
			return "";
		}
	}
	
	
	
	/****
	 * 时间格式转换
	 *@author robert  Aug 11, 2008
	 * @param strDate    格式：yyyy/MM/dd HH:mm:ss
	 * @return  格式：yyyy-MM-dd HH:mm:ss
	 */
	public static String changeDateFormat(String strDate)
	{
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		
		SimpleDateFormat formatter_temp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		try {
			Date temp_date = formatter.parse(strDate);
			
			StringBuffer bdate = new StringBuffer(formatter_temp.format(temp_date));

			return bdate.toString();
			
			
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		return "";
	}
	
	
}
